<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use App\Models\Type;
use App\Models\Question;

class TypesController extends ApiController
{
    /**
     * 列出所有题目分类
     * GET /api/types/
     */
    public function index()
    {
        return $this->success(
            Type::all()
        );
    }

    /**
     * 添加新题目分类
     * POST /api/types/
     *
     * @auth(2,3)
     */
    public function store(Request $request)
    {
        $type = new Type();
        $type->parent_id = $request->input('parent_id');
        $type->type_name = $request->input('type_name');
        $type->save();
        return $this->success();
    }

    /**
     * 修改题目分类
     * PUT /api/types/{id}
     *
     * @auth(2,3)
     */
    public function update($id, Request $request)
    {
        $type = Type::where('id', $id)->first();
        if ($type === null) {
            return $this->error('没有找到该分类');
        }
        $type->parent_id = $request->input('parent_id');
        $type->type_name = $request->input('type_name');
        $type->save();
        return $this->success();
    }

    /**
     * 删除题目分类
     * DELETE /api/types/{id}
     *
     * @auth(2,3)
     */
    public function destory($id)
    {
        $type = Type::where('id', $id)->first();
        if ($type === null) {
            return $this->error('没有找到该分类');
        }
        $count = Question::where('question_type', $id)->count();
        if ($count > 0) {
            return $this->error('该分类下仍有题目，请先移除后再删除');
        } else {
            $type->destroy();
            return $this->success('ok');
        }
    }
}
